/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.admin.client.components;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.elf.gwt.admin.client.AdminComponentController;
import com.elf.gwt.common.client.access.RequestParameter;
import com.elf.gwt.common.client.model.AccountAdministrationModel;
import com.elf.gwt.common.client.model.AccountsAdministrationMetaModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 *  
 */
public class AccountsAdministrationComponent extends EditTableComponent
{
	protected static final String Query = "Query";
	protected static final String ToggleWholesale = "ToggleWholesale";

	protected static EditOrderComponent editOrderComponent = null;
	
	protected List<AccountAdministrationModel> accountAdministrationModels;
	protected AccountAdministrationModel selectedAccountAdministrationModel;
	protected AccountsAdministrationMetaModel accountsAdministrationMetaModel = null;
	protected FormPanel formPanel = null;
	protected Button newButton;
	protected TextBox keywordsTextBox;

	protected DialogBox actionsDialog;
	/**
	 * Constructor
	 */
	public AccountsAdministrationComponent(AdminComponentController controller, String stylePrefix)
	{
		super(controller, stylePrefix);
		accountAdministrationModels = new ArrayList<AccountAdministrationModel>();
		paginate = true;
		tableType = "accounts";
	}


	public void additionalRequestParameters()
	{
		if (action != null && action.equals(ToggleWholesale))
		{
			addRequestParameter(new RequestParameter("accountAdministrationId", selectedAccountAdministrationModel.getId()));
		}
		//else if (action != null && action.equals(Query))
		//{
			Iterator<String> iterElements = elements.keySet().iterator();
			while (iterElements.hasNext())
			{
				String key = iterElements.next();
				Widget widget = elements.get(key);
				String value = CommonUtils.getValue(widget);
				if (value != null && value.length() > 0) addRequestParameter(new RequestParameter(key, value));
			} 
		//}
		super.additionalRequestParameters();
	}

	protected void buildMetaModel(JSONObject jsonObject) throws Exception
	{
		super.buildMetaModel(jsonObject);
		accountsAdministrationMetaModel = new AccountsAdministrationMetaModel(jsonObject);
	}

	protected void buildModel(JSONArray jsonArray) throws Exception
	{
		accountAdministrationModels.clear();
		super.buildModel(jsonArray);
	}

	protected void buildModel(JSONObject jsonObject) throws Exception
	{
		AccountAdministrationModel model = new AccountAdministrationModel(jsonObject);
		accountAdministrationModels.add(model);
	}

	//Using on Built to slip in extra fields at top of component
	public void onBuilt()
	{
		Grid grid = new Grid(1,3);
		int numrow = 0;
		if (keywordsTextBox == null) keywordsTextBox = new TextBox(); 
		elements.put("keywords", keywordsTextBox);
		grid.setText(numrow, 0, "Keywords");
		grid.setWidget(numrow, 1, keywordsTextBox);
		keywordsTextBox.addKeyUpHandler(searchKeyboardHandler);
		Button searchButton = new Button("search", searchHandler);
		searchButton.addStyleName("ComponentLink");
		grid.setWidget(numrow, 2, searchButton);
		numrow++;

		insert(grid, 2);
		
		super.onBuilt();
	}

	public void buildFromModel() throws Exception
	{
		numberOfTableEntries = accountAdministrationModels.size();
		numberOfTableColumns = 14;
		extraRows = 0;

		super.buildFromModel();
		formPanel = new FormPanel("_blank");
		add(formPanel);
	}

	public void displayHeader(Grid grid) {
		grid.setText(0, 0, "Actions");
		grid.setText(0, 1, "Can Login");
		grid.setText(0, 2, "First Name");
		grid.setText(0, 3, "Last Name");
		grid.setText(0, 4, "Email");
		grid.setText(0, 5, "Telephone");
		grid.setText(0, 6, "Fax");
		grid.setText(0, 7, "Wholesale");
		grid.setText(0, 8, "Date Created");
		grid.setText(0, 9, "Date Modified");
		grid.setText(0, 10, "Last Login");
		grid.setText(0, 11, "Logins");
		grid.setText(0, 12, "Reviews");
		grid.setText(0, 13, "Country");
	}

	public void displayRow(Grid grid, int row, int entryIndex) {
		displayRow(grid, row, accountAdministrationModels.get(entryIndex));
	}

	public void displayEmptyRow(Grid grid, int row) {
	}

	public void displayRow(Grid grid, int row, AccountAdministrationModel model) 
	{
		InlineLabel actionsLabel = new InlineLabel("actions");
		actionsLabel.setStyleName("ComponentLink");
		actionsLabel.addStyleName("index:"+(row-1));
		actionsLabel.addClickHandler(actionsClickHandler);
		grid.setWidget(row, 0, actionsLabel);
		
		DateTimeFormat df = CommonUtils.dateFormat;

		if (model.isLogin())
			grid.setWidget(row, 1, new Image(getImageCommonDirectory() + "icon_status_green.gif"));
		else
			grid.setWidget(row, 1, new Image(getImageCommonDirectory() + "icon_status_red.gif"));
		grid.getCellFormatter().setHorizontalAlignment(row, 0, HasHorizontalAlignment.ALIGN_CENTER);
		grid.setText(row, 2, model.getFirstname());
		grid.setText(row, 3, model.getLastname());
		grid.setText(row, 4, model.getEmail());
		grid.setText(row, 5, model.getTelephone());
		grid.setText(row, 6, model.getFax());

		Grid wholesaleGrid = new Grid(1, 3);
		if (model.isWholesale())
		{
			wholesaleGrid.setWidget(0, 0, new Image(getImageCommonDirectory() + "icon_status_green.gif"));
			wholesaleGrid.setWidget(0, 1, new InlineHTML("&nbsp;"));
			Image offImage = new Image(getImageCommonDirectory() + "icon_status_red_off.gif");
			offImage.addStyleName("ComponentLink");
			offImage.addStyleName("index:"+(row-1));
			offImage.addClickHandler(wholesaleClickHandler);
			wholesaleGrid.setWidget(0, 2, offImage);
		}
		else
		{
			Image offImage = new Image(getImageCommonDirectory() + "icon_status_green_off.gif");
			offImage.addStyleName("ComponentLink");
			offImage.addStyleName("index:"+(row-1));
			offImage.addClickHandler(wholesaleClickHandler);
			wholesaleGrid.setWidget(0, 0, offImage);
			wholesaleGrid.setWidget(0, 1, new InlineHTML("&nbsp;"));
			wholesaleGrid.setWidget(0, 2, new Image(getImageCommonDirectory() + "icon_status_red.gif"));
		}
		grid.setWidget(row, 7, wholesaleGrid);
		grid.getCellFormatter().setHorizontalAlignment(row, 6, HasHorizontalAlignment.ALIGN_CENTER);

		grid.setText(row, 8, df.format(model.getDateCreated()));
		if (model.getDateModified() != null) grid.setText(row, 9, df.format(model.getDateModified()));
		if (model.getLastLogin() != null) grid.setText(row, 10, df.format(model.getLastLogin()));
		grid.setText(row, 11, String.valueOf(model.getNumberOfLogins()));
		grid.setText(row, 12, String.valueOf(model.getNumberOfReviews()));
		grid.setText(row, 13, model.getCountryName());

	}

	public List<AccountAdministrationModel> getAccountAdministrationModels() {
		return accountAdministrationModels;
	}

	protected ClickHandler wholesaleClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedAccountAdministrationModel = accountAdministrationModels.get(index);
			action = ToggleWholesale;
			build(true);
		}
	};

	protected ClickHandler actionsClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			actionsDialog = new DialogBox();

			actionsDialog.setStyleName(getHandle()+ "ActionsDialogBox");
			actionsDialog.addStyleName("DialogBox");

			VerticalPanel dialogContents = new VerticalPanel();

			InlineLabel userLoginLabel = new InlineLabel("login");
			userLoginLabel.setStyleName("ComponentLink");
			userLoginLabel.addStyleName("index:"+index);
			userLoginLabel.addClickHandler(userLoginClickHandler);
			dialogContents.add(userLoginLabel);

			InlineLabel editLabel = new InlineLabel("details");
			editLabel.setStyleName("ComponentLink");
			editLabel.addStyleName("index:"+index);
			editLabel.addClickHandler(editClickHandler);
			dialogContents.add(editLabel);

			InlineLabel quoteLabel = new InlineLabel("create quote");
			quoteLabel.setStyleName("ComponentLink");
			quoteLabel.addStyleName("index:"+index);
			quoteLabel.addClickHandler(quoteClickHandler);
			dialogContents.add(quoteLabel);

			InlineLabel ordersLabel = new InlineLabel("view quotes and orders");
			ordersLabel.setStyleName("ComponentLink");
			ordersLabel.addStyleName("index:"+index);
			ordersLabel.addClickHandler(viewOrdersClickHandler);
			dialogContents.add(ordersLabel);
			
			actionsDialog.setWidget(dialogContents);
			actionsDialog.setPopupPosition(source.getAbsoluteLeft(), source.getAbsoluteTop()-5);
			actionsDialog.setAutoHideEnabled(true);
			actionsDialog.show();
		}
	};

	protected ClickHandler userLoginClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			actionsDialog.hide();
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedAccountAdministrationModel = accountAdministrationModels.get(index);

			formPanel.clear();
			formPanel.setMethod(FormPanel.METHOD_POST);
			formPanel.setAction(accountsAdministrationMetaModel.getStoreUrl());
			FlowPanel fpanel = new FlowPanel();
			fpanel.add(new Hidden("accountId", String.valueOf(AdminComponentController.accountComponent.getAccountModel().getId())));
			fpanel.add(new Hidden("accountSession", AdminComponentController.accountComponent.getAccountModel().getSession()));
			fpanel.add(new Hidden("languageId", String.valueOf(AdminComponentController.languagesAdministrationComponent.getLanguageModel().getId())));
			fpanel.add(new Hidden("target_accountId", String.valueOf(selectedAccountAdministrationModel.getId())));
			formPanel.add(fpanel);
			formPanel.submit();
		}
	};

	protected ClickHandler editClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			actionsDialog.hide();
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedAccountAdministrationModel = accountAdministrationModels.get(index);
			String history = "EditAccountComponent--" + selectedGroupId + "--" + selectedAccountAdministrationModel.getId();
			onSelection(history);
		}
	};

	protected ClickHandler quoteClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			actionsDialog.hide();
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedAccountAdministrationModel = accountAdministrationModels.get(index);

			if (editOrderComponent == null) editOrderComponent = (EditOrderComponent)controller.getComponent("EditOrderComponent");
			//This hides the action from the history.
			editOrderComponent.action = EditOrderComponent.InsertQuote;
			int group = selectedGroupId + 1;
			
			String history = "EditOrderComponent--" + group + "--0--" + selectedAccountAdministrationModel.getId();
			onSelection(history);
		}
	};

	protected ClickHandler viewOrdersClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			actionsDialog.hide();
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedAccountAdministrationModel = accountAdministrationModels.get(index);
			int group = selectedGroupId + 1;
			String history = "AccountsComponent--" + group + "--" + selectedAccountAdministrationModel.getId();
			onSelection(history);
		}
	};

	public void updateButtonPanel() {
		if (buttonPanel == null)
		{
			buttonPanel = new HorizontalPanel();
			buttonPanel.setStyleName("ZButtons");

			newButton = new Button("new", newHandler);
			newButton.addStyleName("ComponentLink");
			buttonPanel.add(newButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

		}
		newButton.setVisible(!edit);
	}

	protected ClickHandler newHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			String history = "EditAccountComponent--" + selectedGroupId + "--0";
			onSelection(history);
		}
	};

	protected ClickHandler searchHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			action = Query;
			build(true);
		}
	};
	
	protected KeyUpHandler searchKeyboardHandler = new KeyUpHandler() {
		public void onKeyUp(KeyUpEvent event) {
			if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
				action = Query;
				build(true);
			}
		}
	};
}
